package com.yulang.web.security;

import com.yulang.web.exception.BusinessException;
import com.yulang.web.pojo.SysPermission;
import com.yulang.web.pojo.SysUser;
import com.yulang.web.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractUserDetailFactory implements UserDetailsService {

    @Autowired
    private SysPermissionService sysPermissionService;

    abstract SysUser findSysUser(String userNameOrMobile);

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user = findSysUser(s);
        findSysPermission(user);
        return user;
    }

    private void findSysPermission(SysUser user){
        if(user==null){
            throw new BusinessException("用户不存在！");
        }
        List<GrantedAuthority> list = new ArrayList<>();
        List<SysPermission> sysPermissions = sysPermissionService.selectPermissionByUserId(user.getId().toString());
        sysPermissions.forEach(sysPermission -> list.add(new SimpleGrantedAuthority(sysPermission.getCode())));
        user.setAuthorities(list);
        user.setPermissions(sysPermissions);
    }

}
